﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;

namespace FileNameConverter
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private Files OriginalFiles = new Files();  //原始陣列*用來存編輯前之名稱
        private Files EditedFiles = new Files();    //編輯陣列*用來存編輯後之名稱
        private int pageLength = 0;                 //頁碼長度
        private string sourcePath = @"C:";         //來源路徑
        private string targetPath = @"C:";         //目標路徑
        private string createDirectory = @"檔名修正\";  //自動產生的資料夾，用來存放轉換後的檔案

        private bool actionComplited = true;        //儲存此執行動作是否完成
        public bool ActionComplited
        {
            get { return actionComplited; }
            set { actionComplited = value; }
        }
        private bool isFromHead = true;          //來源是否為由前往後掃描，提供form2使用
        public bool IsFromHead
        {
            get { return isFromHead; }
            set { isFromHead = value; }
        }
        private uint minimumPage = 0, maxmumPage = 0;//自動轉換頁碼，正確來源的頁碼最大最小值
        public uint MinimumPage
        {
            get { return minimumPage; }
            set { minimumPage = value; }
        }
        public uint MaxmumPage
        {
            get { return maxmumPage; }
            set { maxmumPage = value; }
        }
        //private bool IsEdit = false;

        
        private void CleanDataGridView1Selected()
        {
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                row.Selected = false;
            }
        }

        //dataGridView1加入資料(一筆資料)
        private void Add_Data_To_datGridView1(int idkey, string filename, uint page)
        {
            string pageFormat = "D"+pageLength.ToString();
            if(page ==0)
                dataGridView1.Rows.Add(idkey.ToString(), filename, "");
            else
                dataGridView1.Rows.Add(idkey.ToString(), filename, page.ToString(pageFormat));
        }
        


        //dataGridView1刪除資料(一筆資料)
        private void Delete_Date_From_dataGridView1(int idkey)
        {
            int rowIndex = -1;
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                if (int.Parse(row.Cells[0].Value.ToString()) == idkey)
                    rowIndex = dataGridView1.Rows.IndexOf(row);
            }
            if (rowIndex != -1)
                dataGridView1.Rows.RemoveAt(rowIndex);
        }



        //將字串陣列解析，並將資料加入到dataGridView、原始陣列及編輯陣列
        private void Add_Data_To_dataGridView1_And_Files(string[] filenames)
        {
            File file = new File(0, "", 0, "");
            for (int i = 0; i < filenames.Count(); i++)
            {
                file.IDkey = i;
                file.Extension = Path.GetExtension(filenames[i]);
                file.Filename = Path.GetFileName(filenames[i]);
                file.Filename = file.Filename.Substring(0, file.Filename.Length - file.Extension.Length - pageLength);
                //頁碼string轉換成int
                if (toolStripComboBox2.SelectedIndex == 0)
                    file.Page = 0;
                else
                    file.Page = Convert.ToUInt32(filenames[i].Substring(filenames[i].Length - file.Extension.Length - pageLength, pageLength));
                //加入原始陣列
                OriginalFiles.AddFile(file.IDkey, file.Filename, file.Page, file.Extension);
                //資料加入dataGridView1
                Add_Data_To_datGridView1(file.IDkey, file.Filename, file.Page);
            }
            
            
            //排序dataGridView1，檔名->頁碼
            dataGridView1.Sort(dataGridView1.Columns[2], ListSortDirection.Ascending);
            dataGridView1.Sort(dataGridView1.Columns[1], ListSortDirection.Ascending);
            //原始陣列備份至編輯陣列
            OriginalFiles.CopyTo(EditedFiles);
        }



        //清除資料從dataGridView1、原始陣列及編輯陣列
        private void Clear_Data_From_dataGridView1_And_Files()
        {
            //清除dataGridView
            int RowsCount = dataGridView1.Rows.Count;
            for (int i = 0; i < RowsCount; i++)
                dataGridView1.Rows.RemoveAt(0);
            //清除陣列
            OriginalFiles.RemoveAll();
            EditedFiles.RemoveAll();
            dataGridView1.Refresh();
        }


        
        //openFile功能
        private void OpenFile()
        {
            openFileDialog1.Filter = "JPG(*.jpg)|*.jpg|所有檔案|*.*";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    //Clear All data
                    Clear_Data_From_dataGridView1_And_Files();
                    //Insert code to read the stream here.
                    //將選取之檔名字串陣列解析，並將資料加入到dataGridView1、原始陣列及編輯陣列
                    Add_Data_To_dataGridView1_And_Files(openFileDialog1.FileNames);

                    //儲存來源路徑
                    sourcePath = Path.GetDirectoryName(openFileDialog1.FileNames[0]) + @"\";
                    targetPath = sourcePath;
                    toolStripStatusLabel1.Text = "來源路徑\"" + sourcePath + "\"";
                    //IsEdit = false;
                }
                catch (Exception)
                {
                    MessageBox.Show("請確認來源檔是否正確");
                    actionComplited = false;
                }
            }
            
        }


        //改寫檔名，用來委派的函式
        private void ResetFile(File file, string filename, uint page)
        {
            file.Filename = filename;
            file.Page = page;
        }
        //讀取dataGridView1到EditFiles，回傳讀取是否正確
        private void LoadDataGridView1toEditedFiles()
        {
            int getIDkey = -1;
            string getFilename = "";
            uint getPage = 0;
            CleanDataGridView1Selected();
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                try
                {
                    getPage = Convert.ToUInt32(row.Cells[2].Value);
                }
                catch(Exception)
                {
                    //頁碼格式不正確
                    actionComplited = false;
                    row.Cells[2].Selected = true;
                }
                if (row.Cells[2].Value.ToString().Length > pageLength)
                {
                    //頁碼長度過長
                    actionComplited = false;
                    row.Cells[2].Selected = true;
                }
            }
            if (actionComplited)
            {
                foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    getIDkey = Convert.ToInt32(row.Cells[0].Value);
                    getFilename = row.Cells[1].Value.ToString();
                    getPage = Convert.ToUInt32(row.Cells[2].Value);
                    //使用委派處理File物件
                    EditedFiles.ProcessFile(ResetFile, getIDkey, getFilename, getPage);
                }
            }
        }



        //檔案複製，且回報背景工作進度
        private void Saving()
        {
            int Complited = 0;

            int FileNumber = OriginalFiles.FilesCount();
            string[] SourceFullPath = OriginalFiles.getFullName(sourcePath, pageLength);
            string[] TargetFullPath = EditedFiles.getFullName(targetPath, pageLength);
            for (int i = 0; i < FileNumber; i++)
            {
                try
                {
                    Complited = (i * 100) / FileNumber;
                    backgroundWorker1.ReportProgress(Complited, "儲存中..." + Complited.ToString() + "%"); //進度回報
                    System.IO.File.Copy(SourceFullPath[i], TargetFullPath[i]);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message + "\n" + "請確認是否重複轉換相同檔案");
                    toolStripStatusLabel1.Text = "請確認是否重複轉換相同檔案";
                    actionComplited = false;
                    break;
                }
            }
            if (actionComplited)
            {
                Complited = 100;
                backgroundWorker1.ReportProgress(Complited, "已完成..." + Complited.ToString() + "%"); //進度回報
                //完成複製
            }
        }



        //saveFile功能
        private void SaveFile()
        {
            //將dataGridView1的檔案存進
            LoadDataGridView1toEditedFiles();
            if (actionComplited)
            {
                //紀錄選擇儲存路徑
                targetPath = sourcePath + createDirectory;
                if (!System.IO.Directory.Exists(targetPath))
                {
                    System.IO.Directory.CreateDirectory(targetPath);
                }

                //開始複製
                Saving();
                //複製完成
            }
            else
            {
                MessageBox.Show("頁碼格式不正確");
                toolStripStatusLabel1.Text = "頁碼格式不正確";
            }
        }




        //搜尋功能，回傳符合項目之個數
        private int Search(string sample)
        {
            int machCount = 0;
            string getFileName, getPage;

            CleanDataGridView1Selected();
            if (dataGridView1.Rows.Count > 0 && toolStripTextBox1.Text != "")
            {
                foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    getFileName = row.Cells[1].Value.ToString();
                    getPage = row.Cells[2].Value.ToString();
                    if (getFileName.IndexOf(sample) > -1)
                    {
                        row.Cells[1].Selected = true;
                        machCount++;
                    }
                    else
                        row.Cells[1].Selected = false;
                }
            }

            return machCount;
        }




        //搜尋與取代，將dataGridView1中已選擇的欄位, 取代欄位中字串的子字串
        private void SwapSubString()
        {
            string oriStr, searchStr = toolStripTextBox1.Text, subStr = toolStripTextBox2.Text;
            string tempStrHead, tempStrEnd;
            int index = -1, seachLen = searchStr.Length;
            foreach (DataGridViewCell cell in dataGridView1.SelectedCells)
            {
                //oriStr = tempStrHead = tempStrEnd = "";
                oriStr = cell.Value.ToString();
                index = oriStr.IndexOf(searchStr);
                if (index > 0)
                    tempStrHead = oriStr.Substring(0, index);
                else
                    tempStrHead = "";
                if (index + seachLen < oriStr.Length)
                    tempStrEnd = oriStr.Substring(index + seachLen, oriStr.Length - index - seachLen);
                else
                    tempStrEnd = "";
                oriStr = tempStrHead + subStr + tempStrEnd;
                cell.Value = oriStr;
            }
        }




        //自動轉換核心，檢查是否為可轉換之檔案，回傳︰-1正確，0檔名不相同，1頁碼不連續
        private int FilePageConverter()
        {
            //檢查檔案是否可轉換
            string tmpFilename = dataGridView1.Rows[0].Cells[1].Value.ToString();
            uint tempPagenum = Convert.ToUInt32(dataGridView1.Rows[0].Cells[2].Value);

            //檢查頁碼是否連續
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                if (!tmpFilename.Equals(row.Cells[1].Value))
                    return 0;
                if (Convert.ToInt32(row.Cells[2].Value) != tempPagenum++)
                    return 1;
            }
            //檢查結束
            
            //自動轉換，結果顯示於dataGridView1
            if (isFromHead)
            {
                tempPagenum = minimumPage;
                foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    row.Cells[2].Value = tempPagenum;
                    tempPagenum += 2;
                }
            }
            else
            {
                tempPagenum = maxmumPage;
                foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    row.Cells[2].Value = tempPagenum;
                    tempPagenum -= 2;
                }
            }
            return -1;
        }



        //自動轉換功能，回傳是否成功
        private void AutoConvertion()
        {
            //開啟檔案
            OpenFile();
            if (actionComplited)
            {
                //開啟From2設定選項
                Form2 myFrom2 = new Form2();
                myFrom2.MainFrom = this;
                myFrom2.ShowDialog(this);
                if (actionComplited)
                {
                    //自動編輯轉換頁碼，取得轉換結果
                    int ConvertReport = FilePageConverter();
                    switch (ConvertReport)
                    {
                        case -1:
                            //開始儲存轉換結果
                            //暫時關閉相關功能之按鈕，背景工作完成後開啟
                            toolStrip1.Enabled = false;
                            menuStrip1.Enabled = false;
                            //開啟進度調toolStripProgressBar1，背景工作完成後關閉
                            toolStripProgressBar1.Enabled = true;
                            toolStripProgressBar1.Visible = true;
                            //開始背景執行續，backgroundWorker1
                            backgroundWorker1.RunWorkerAsync();
                            break;
                        case 1:
                            MessageBox.Show("檔案名稱並不完全相同，請確認為同一掃描來源");
                            actionComplited = false;
                            break;
                        case 0:
                            MessageBox.Show("檔案名稱並不完全相同，請確認為同一掃描來源");
                            actionComplited = false;
                            break;
                        default:
                            actionComplited =false;
                            break;
                    }
                }
                else
                    toolStripStatusLabel1.Text = "取消自動轉換頁碼";
            }
        }



        private void Form1_Load(object sender, EventArgs e)
        {
            toolStripStatusLabel1.Text = "就緒";
            toolStripComboBox1.SelectedIndex = 1;
            toolStripComboBox2.SelectedIndex = 3;
            pageLength = toolStripComboBox2.SelectedIndex;
            //toolStripStatusLabel1.Text = pageLength.ToString();
        }



        private void Form1_SizeChanged(object sender, EventArgs e)
        {
            DataGridView1_AutoSize();
        }



        private void dataGridView1_SizeChanged(object sender, EventArgs e)
        {
            dataGridView1.Columns[1].Width = dataGridView1.Size.Width - 100 - 43;
            dataGridView1.Columns[2].Width = 100;
            dataGridView1.RowHeadersWidth = 41;
        }



        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            actionComplited = true;
            OpenFile();
        }


        //儲存按鈕
        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            actionComplited = true;
            if (dataGridView1.Rows.Count > 0)
            {
                //暫時關閉相關功能之按鈕，背景工作完成後開啟
                toolStrip1.Enabled = false;
                menuStrip1.Enabled = false;
                //開啟進度調toolStripProgressBar1，背景工作完成後關閉
                toolStripProgressBar1.Enabled = true;
                toolStripProgressBar1.Visible = true;
                //開始背景執行續，backgroundWorker1
                backgroundWorker1.RunWorkerAsync();
            }
        }


        //自動轉換頁碼按鈕事件
        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            actionComplited = true;
            if (pageLength != 0)
                AutoConvertion();
            else
                actionComplited = false;
        }



        //開始背景工作事件
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            SaveFile();
        }



        //背景工作狀態變更事件
        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            toolStripStatusLabel1.Text = e.UserState.ToString();
            toolStripProgressBar1.Value = e.ProgressPercentage;
        }



        //背景工作完成事件
        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            //開啟相關功能之按鈕
            toolStrip1.Enabled = true;
            menuStrip1.Enabled = true;
            //關閉進度條
            toolStripProgressBar1.Enabled = false;
            toolStripProgressBar1.Visible = false;
            if (actionComplited)
            {
                toolStripStatusLabel1.Text = "儲存路徑\"" + targetPath + "\"";
                MessageBox.Show("Save Complited.");
            }
            //自動開啟資料夾
            ProcessStartInfo startInfo = new ProcessStartInfo("explorer.exe");
            startInfo.Arguments = targetPath + "\"";
            Process.Start(startInfo);
        }



        //表格被編輯過後發生之事件
        private void dataGridView1_CellParsing(object sender, DataGridViewCellParsingEventArgs e)
        {
            //發生於已經修改儲存格值後，該儲存格離開編輯模式時
            toolStripStatusLabel1.Text = "編輯中";
            //IsEdit = true; ;
        }



        //頁碼變更事件
        private void toolStripComboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            pageLength = toolStripComboBox2.SelectedIndex;
        }



        //搜尋與取代功能變更事件
        private void toolStripComboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (toolStripComboBox1.SelectedIndex == 0)
            {
                toolStripTextBox2.Visible = true;
                toolStripButton5.Visible = true;
            }
            else
            {
                toolStripTextBox2.Visible = false;
                toolStripButton5.Visible = false;
            }

        }


        //搜尋按鈕事件, 開始搜尋
        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            toolStripStatusLabel1.Text = "共有 " + Search(toolStripTextBox1.Text).ToString() + " 個符合項目";
        }



        //在搜尋文字攔中按下enter之事件
        private void toolStripTextBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (Convert.ToInt32(e.KeyChar) == 13)
            {
                toolStripStatusLabel1.Text = "共有 " + Search(toolStripTextBox1.Text).ToString() + " 個符合項目";
            }
        }


        //搜尋與取代按鈕事件
        private void toolStripButton5_Click(object sender, EventArgs e)
        {
            //搜尋，選取dataGridView1中有包涵
            string searchStr = toolStripTextBox1.Text;
            int number = Search(searchStr);
            //取代
            if (number > 0)
                SwapSubString();
            else
                MessageBox.Show("無此字串\"" + searchStr + "\"");
            toolStripStatusLabel1.Text = "共有 " + number + " 個項目完成取代";
        }


        //在搜尋與取代項目攔中輸入Enter之事件
        private void toolStripTextBox2_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (Convert.ToInt32(e.KeyChar) == 13)
            {
                //搜尋，選取dataGridView1中有包涵
                string searchStr = toolStripTextBox1.Text;
                int number = Search(searchStr);
                //取代
                if (number > 0)
                    SwapSubString();
                else
                    MessageBox.Show("無此字串\"" + searchStr + "\"");
                toolStripStatusLabel1.Text = "共有 " + number + " 個項目完成取代";
            }
        }

        private void ToolStripMenuItem4_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            Form3 myForm3 = new Form3();
            myForm3.ShowDialog(this);
        }
    }
}
